<?php

namespace ChannelThrift\Controller;

require_once MODULE_PATH . 'Org/Thrift/Lib/Thrift/ClassLoader/ThriftClassLoader.php';

use Services\AuctionService\AuctionServiceClient;
use Services\BailService\BailServiceClient;
use Thrift\ClassLoader\ThriftClassLoader;
use \Common\Org\PhpRedis;

$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift', MODULE_PATH . 'Org/Thrift/Lib');
$loader->registerDefinition('Services', MODULE_PATH . 'Org/Thrift/gen-php');
$loader->register();

use Thrift\Protocol\TBinaryProtocol;
use Thrift\Protocol\TMultiplexedProtocol;
use Thrift\Transport\THttpClient;
use Thrift\Transport\TBufferedTransport;
use Thrift\Exception\TException;


class ClientController extends CommonController
{
    public function tester(){
        //echo date('Y-m-d H:i:s',1498025760);
        echo time_left_to_24();

    }
//计算到0点的剩余时间（秒）
    function time_left_to_24(){
        $stime = strtotime(date('Y-m-d 23:59:59'));
        $time = $stime - time();
        return $time;
    }
    public function runBail()
    {
        $api_url = I('request.api_url');

        $api_route = I('request.route');

        $option = I('request.params');
        //          $api_route = 'getDealer';
        //            $option = array(
        //                'dealer_id'=>525,
        //            );
        //        $option = json_decode($api_params,true);
        //        if(json_last_error() != JSON_ERROR_NONE){
        //            exit(json_encode(array('code'=>500,'msg'=>'参数异常')));
        //        }

        try {
            $handle = new THttpClient($api_url, 80, '/Bail/run');

            $transport = new TBufferedTransport($handle);

            $protocol = new TBinaryProtocol($transport);

            $bailProtocol = new TMultiplexedProtocol($protocol, 'BailService');

            $bailService = new BailServiceClient($bailProtocol);
              switch($api_route){
                  case 'getDealer':
                       $dealer_id = intval($option['dealer_id']);

                       $result =  $bailService->getDealerBail($dealer_id);

                       break;
                  case 'dec':
                      $dealer_id = intval($option['dealer_id']);
                      $amount = $option['amount'];
                      $useType = $option['usetype'];
                      $useDetail = $option['usedetail'];
                      $orderId  = $option['order_id'];
                      $result = $bailService->decBail($dealer_id,$amount,$useType,$useDetail,$orderId);
                      break;
                  case 'inc':
                      $dealer_id = intval($option['dealer_id']);
                      $amount = $option['amount'];
                      $useDetail = $option['usedetail'];
                      $rechargeNo = $option['rechargeno'];
                      $rechargeId = $option['rechargeid'];
                      $rechargeMethod = $option['rechargemethod'];
                      $collectionId = $option['collectionId'];
                      $result = $bailService->incBail($dealer_id,$amount,$useDetail,$rechargeNo,$rechargeId,$rechargeMethod,$collectionId);
                      break;
                  case 'freeze':
                      $dealer_id = intval($option['dealer_id']);
                      $amount = $option['amount'];
                      $orderId = $option['orderid'];
                      $result = $bailService->freezeBail($dealer_id,$amount,$orderId);
                      break;
                  case 'unfreeze':
                      $dealer_id = $option['dealer_id'];
                      $amount = $option['amount'];
                      $orderId = $option['order_id'];
                      $result = $bailService->unfreezeBail($dealer_id,$orderId);
                      break;
                  case 'unfreezeDec':
                      $dealer_id = intval($option['dealer_id']);
                      $amount = $option['amount'];
                      $orderId = $option['order_id'];
                      $decAmount = $option['dec_amount'];
                      $useType = $option['usetype'];
                      $useDetail = $option['usedetail'];
                      $result = $bailService->unfreezeDecBail($dealer_id,$orderId,$decAmount,$useType,$useDetail);
                      break;
                  case 'logs':
                      $dealer_id = intval($option['dealer_id']);
                      $pageSize = $option['pageSize'];
                      $page = $option['page'];
                      $useTime = $option['useTime'];
                      $useType = $option['useType'];
                      $isUnFree = $option['isUnFree'];
                      $payMethod = $option['payMethod'];
                      $result = $bailService->getBailLogsByDealerId($dealer_id,$useType,$useTime,$page,$pageSize,$isUnFree,$payMethod);
                      break;
              }
              exit(json_encode($result));
            //$dealer = $bailService->getDealerBail(55);
            //dump($dealer);
            //$result = $bailService->decBail(55,1000,'','');
            //dump($result);
            //$inc = $bailService->incBail(55,1000,'','');
            //dump($inc);
            //$free = $bailService->freezeBail(55,2000,218);
            //dump($free);
            //$log = $bailService->unfreezeBail(55,2000,218);
            //dump($log);
            //$result = $bailService->unfreezeDecBail(55,1000,218,20,'','');
            //dump($result);
        } catch (TException $tx) {
            exit(json_encode(array('code'=>$tx->getCode(),'message'=>$tx->getMessage())));
          //  print 'TException: ' . $tx->getCode() . ' ' . $tx->getMessage() . "\n";
        }
    }


    public function bid()
    {
        try {
            $handle = new THttpClient('liguohua.auction.weaver.s.isou365.cn', 80, '/Auction/run');
            //$handle = new TSocket('localhost', 9090);

            $transport = new TBufferedTransport($handle);
            $protocol = new TBinaryProtocol($transport);
            $auctionProtocol = new TMultiplexedProtocol($protocol, 'AuctionService');
            $auctionService = new AuctionServiceClient($auctionProtocol);

            $dealer_id = I('request.dealer_id');
            $order_id = I('request.order_id');
            $price = I('request.price');
            $res = $auctionService->bid($dealer_id, $order_id, $price,0);
            dump($res);
        } catch (TException $tx) {
            print 'TException: ' . $tx->getCode() . ' ' . $tx->getMessage() . "\n";
        }
    }

    public function bidding()
    {
        try {

            $handle = new THttpClient('songaimin.weaver.clcw.com.cn', 80, '/Auction/run');
            //$handle = new TSocket('localhost', 9090);

            $transport = new TBufferedTransport($handle);
            $protocol = new TBinaryProtocol($transport);
            $auctionProtocol = new TMultiplexedProtocol($protocol, 'AuctionService');
            $auctionService = new AuctionServiceClient($auctionProtocol);

            $res = $auctionService->bidding(528, 2423, 901,300,0,0);
            var_dump($res);
        } catch (TException $tx) {
            print 'TException: ' . $tx->getCode() . ' ' . $tx->getMessage() . "\n";
        }
    }
    public function cusBidding()
    {
        try {
            $handle = new THttpClient('liguohua.auction.weaver.s.isou365.cn', 80, '/Auction/run');
            $transport = new TBufferedTransport($handle);
            $protocol = new TBinaryProtocol($transport);
            $auctionProtocol = new TMultiplexedProtocol($protocol, 'AuctionService');
            $auctionService = new AuctionServiceClient($auctionProtocol);

            $res = $auctionService->cusBidding(528, 2423, 901,300,0,0);
            var_dump($res);
        } catch (TException $tx) {
            print 'TException: ' . $tx->getCode() . ' ' . $tx->getMessage() . "\n";
        }
    }
    public function test(){
        $orderServ = new \ChannelThrift\Service\OrderService();
        $order = $orderServ-> getOrder(2231);
        dump($order);
        //test();
        //$m = D('ChannelThrift/Aums/Order');
        dump(M());
        //$a = $m->execute("select * from au_setting limit 10");
        //dump($a);
    }



    //---------------------------------sam_utest 201700303-----------------------------------------------
    /**
    @param serviceName 服务模块名
    @param servicePath 服务路径
    @param serviceDomain 服务域名
    @param servicePort 服务端口
    @return thriftclient 
    */
    private function getThriftClient($serviceName,$servicePath,$serviceDomain,$servicePort=80){      
        if (!$serviceName){
            //抛出异常            
            return false;
        }
        $handle = new THttpClient($serviceDomain, $servicePort, $servicePath);
        $transport = new TBufferedTransport($handle);
        $protocol = new TBinaryProtocol($transport);
        $auctionProtocol = new TMultiplexedProtocol($protocol, $serviceName);
        $serviceName='\\Services\\'.$serviceName.'\\'.$serviceName.'Client';
        $client = new $serviceName($auctionProtocol);
        return $client;        
    }



    //测试充值入队
    public function testRecharge(){

        $bcs = new \ChannelThrift\Service\BailCacheService();
        $dealerId = 467;
        $bcs->bailChangePushQueue(1,array('dealer_id'=>$dealerId,'occur_money'=>2000,'use_type'=>1));
        //$dealer = $bcs->getDealerBail($dealerId);
        print_r($dealer);
        exit;



        $listKey = 'AuctionWeaver:Bail:ChangeQueue';
        $redis=new PhpRedis(4);
        $dSummary = $redis->rPop($listKey);        
        $dSummary = json_decode($dSummary,true);
        print_r($dSummary);        
        //$bcs->cleanDealerBail($dealerId);
        //$redis->del($listKey);        
    }



    public function testBidCache(){            
            $bidcache = new \ChannelThrift\Service\BidCacheService();
            $bidcache->test();
            exit;
    }

    public function testsam(){    

        try {

            $bcs = new \ChannelThrift\Service\BailCacheService();
            

            $dealerId = 467;

            // $bcs->cleanDealerBail($dealerId);
            // exit;
            $bcs->bailChangePushQueue(1,array('dealer_id'=>$dealerId,'occur_money'=>2000,'use_type'=>1));
            $dealer = $bcs->getDealerBail($dealerId);
            echo '充后...............';
            print_r($dealer);


            $bcs->bailChangePushQueue(2,array('dealer_id'=>$dealerId,'occur_money'=>2000,'use_type'=>2,'order_id'=>'3352'));
            $dealer = $bcs->getDealerBail($dealerId);
            echo '冻后....................';
            print_r($dealer);

            $bcs->bailChangePushQueue(3,array('dealer_id'=>$dealerId,'occur_money'=>2000,'use_type'=>3,'order_id'=>'3352'));        
            $dealer = $bcs->getDealerBail($dealerId);
            echo '解后.....................';
            print_r($dealer);

        
            // $dealerID = 467;

            // $bcs = new \ChannelThrift\Service\BailCacheService();
            // $dealerId = 467;
            // //$bcs->bailChangePushQueue(1,array('dealer_id'=>$dealerId,'occur_money'=>2000,'use_type'=>1));
            // $dealer = $bcs->getDealerBail($dealerId);
            
            // //$dealer = D('CarDealer', 'Service')->getCarDealer($dealerID);   
            // var_dump($dealer);


            // exit;
            // $client = $this->getThriftClient('BailService','/Bail/run','songaimin.auction.weaver.s.isou365.cn');                                    
            // //$res=$client->incBail(467, 2000, '保证金充值', '201703030001', 1, 3,1);
            // $res = $client->getDealerBail(467);
            // var_dump($res);
            // exit();
        } catch (Exception $e) {
            echo 'TException: ' . $tx->getCode() . ' ' . $tx->getMessage() . "\n";
        }
        
        exit;

     /* $model = new \ChannelThrift\Service\CarDealerService();
      dump($model);
      exit;
      $model->startTrans();
      $bail = new BailService();
      $freePrice = $bail->freezeBail($dealer_id,$freeze_price,$order_id);
      $model->rollback();
      $model->commit();*/


      try {
            $handle = new THttpClient('wangji.weaver.clcw.com.cn', 80, '/Auction/run');
            $transport = new TBufferedTransport($handle);
            $protocol = new TBinaryProtocol($transport);
            $auctionProtocol = new TMultiplexedProtocol($protocol, 'BailService');
            $auctionService = new AuctionServiceClient($auctionProtocol);

            $res = $auctionService->incBail(467, 2000, '保证金充值', '201703030001', 1, 3,1);
            var_dump($res);
        } catch (TException $tx) {
            print 'TException: ' . $tx->getCode() . ' ' . $tx->getMessage() . "\n";
        }
      
    }


}



